import VueRouter from "vue-router";
import Vue from "vue";
import routes from "@/routes/routes";
import store from "@/store";
Vue.use(VueRouter)
//重写$router.push方法
const OldRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function (
    location,
    onComplete=()=>{},
    onAbort=()=>{}){

    OldRouterPush.call(this,location,onComplete,onAbort)
}
//重写$router.replace方法
const OldRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (
    location,
    onComplete=()=>{},
    onAbort=()=>{}){

    OldRouterReplace.call(this,location,onComplete,onAbort)
}

const router = new VueRouter({
    mode:"history",
    routes
})
const whitePath = ["login","home","addCartSuccess","search","shopCart","detail", "register",]
router.beforeEach(async (to,from,next)=>{
    const token = store.state.user.token
    //判断有无token
    if(token){
        //判断是否为登录页,如果是跳首页
        if(to.name === "login"){
            next("/home")
        }else {
            //如果不是登录页且判断是否有用户信息,
            const isUserInfo = !!store.state.user.userInfo.nickName
            //如果有直接放行
            if(isUserInfo){
                next()
            //如果没有发送请求拿到用户信息
            }else {
               try {
                   await store.dispatch("user/getUserInfo")
                   next()
               }catch (e){
                   store.dispatch("user/getRemove")
                   next(`/login?redirect=${to.name}`);
               }
            }
        }
    }else {
        //如果没有token,判断是否在白名单,如果在直接放行
        if(whitePath.includes(to.name)){
            next()
        //如果不在白名单,直接跳到登录页
        }else {
            next(`/login?redirect=${to.name}`);
        }
    }
})
export default router